package com.fantasy9.gameserver.codec;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.fantasy9.gameserver.message.BaseClientMessage;
import com.fantasy9.gameserver.message.ClientMessageRecognizer;

public class BaseMessageDecoder extends CumulativeProtocolDecoder {

	@Override
	protected boolean doDecode(IoSession session, ByteBuffer msg,
			ProtocolDecoderOutput out) throws Exception {
		
		if(msg.prefixedDataAvailable(Integer.SIZE / Byte.SIZE)){
			// Ok we have enough data for msg
			int msgLength = msg.getInt();
			
			if(msgLength < (Integer.SIZE / Byte.SIZE)){
				// This is impossible for normal msg, as Msg Id always exists
				byte[] bytes = new byte[msgLength];
				msg.get(bytes);
				
				return true;
			}
			else{
				int msgId = msg.getInt();
				
				// This is impossible for normal msg, as Msg Id always exists
				byte[] bytes = new byte[msgLength - (Integer.SIZE / Byte.SIZE)];
				msg.get(bytes);
				
				BaseClientMessage clientMsg = ClientMessageRecognizer.getInstance().getClientMessage(msgId);
				
				if(clientMsg != null){
					clientMsg.writeBytes(bytes);
					clientMsg.readFromByteBuffer();
					out.write(clientMsg);
				}
				
				return true;
			}

		}
		return false;
	}

}
